package com.ci.docker.registry.certificate;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Service
public class CertificateService {

    @Value("${docker.registry.certificate.path}")
    private String rootDirPath;

    public List<CertificateInfo> list() {
        File rootFile = new File(rootDirPath);
        if (!rootFile.exists()) {
            return Collections.emptyList();
        }
        File[] files = rootFile.listFiles((dir, name) -> {
            File f = new File(dir, name);
            return f.isDirectory();
        });
        if (files == null || files.length == 0) {
            return Collections.emptyList();
        }
        List<CertificateInfo> infos = new ArrayList<>(files.length);
        for (File file : files) {
            infos.add(new CertificateInfo(file));
        }

        return infos;
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public String add(String name, List<MultipartFile> files) {
        File rootFile = new File(rootDirPath);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        File target = new File(rootFile, name);
        if (target.exists()) {
            throw new RuntimeException("文件:" + target.getAbsolutePath() + "已经存在");
        }
        if (!target.mkdirs()) {
            throw new RuntimeException("文件夹:" + target.getAbsolutePath() + "创建失败");
        }
        for (MultipartFile file : files) {
            if (file == null || file.getOriginalFilename().trim().length() == 0) {
                continue;
            }
            File f = new File(target, file.getOriginalFilename());
            try (InputStream inputStream = file.getInputStream();
                 FileOutputStream stream = new FileOutputStream(f);) {
                byte[] b = new byte[1024];
                int len;
                while ((len = inputStream.read(b)) != -1) {
                    stream.write(b, 0, len);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return "success";
    }

    public String delete(String name) {
        if (!rootDirPath.endsWith("/")) {
            rootDirPath = rootDirPath + "/";
        }
        rootDirPath = rootDirPath + name;
        File file = new File(rootDirPath);
        deleteDir(file);
        return "success";
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    private void deleteDir(File file) {
        File[] files = file.listFiles();
        assert files != null;
        for (File file1 : files) {
            if (file1.isDirectory()) {
                deleteDir(file1);
            } else {
                file1.delete();
            }
        }
        file.delete();
    }
}
